//
//  DefaultHttpClientResponseHandler.m
//  ITV
//
//  Created by inphase on 2017/8/2.
//  Copyright © 2017年 inphase. All rights reserved.
//

#import "DefaultResponseHandler.h"


#if __has_include(<AFNetworking.h>)
#import <MJExtension.h>
#else
#import "MJExtension.h"
#endif


@implementation DefaultResponseHandler

/*
 * 默认实现，对返回数据做数据解析处理，
 * 解析成功并有对应返回类型时，做对应类型转换并返回
 * 解析失败做失败回调
 */
-(void (^)(NSURLSessionTask *, id))success:(void (^)(NSURLSessionTask *, id))success
                                                failure:(void (^)(NSURLSessionTask *, NSError *))failure
                                          responseClass:(__unsafe_unretained Class)classType{
    
    void (^successBlock_noraml)(NSURLSessionTask *operation, id responseObject) = ^(NSURLSessionTask *operation, id responseObject) {
        NSError *error = nil;
        id jsonObject=[NSJSONSerialization JSONObjectWithData:responseObject
                                                      options:NSJSONReadingMutableContainers error:&error];
        if (!error) {
            if (classType != nil) {
                if ([jsonObject isKindOfClass:[NSArray class]]) {
                    success(operation,[classType mj_objectArrayWithKeyValuesArray:jsonObject]);
                }else {
                    success(operation,[classType mj_objectWithKeyValues:jsonObject]);
                }
            }
            else {
                success(operation,jsonObject);
            }
        }else {
            failure(operation,error);
        }
    };
    
    return successBlock_noraml;
}

/*
 * 对失败不做任何处理
 */
- (void (^)(NSURLSessionTask *, NSError *))failure:(void (^)(NSURLSessionTask *, NSError *))failure {
    return failure;
}

@end
